import copy
from concurrent.futures import ThreadPoolExecutor
from time import time
from multiprocessing import Process, Queue

from utils.logging_tool.log_control import Listing_Error
from utils.noticeUtils.dingtalkControl import DingTalkSendMsg
from public_way import public_invoking
from utils.times_tool.time_control import now_time


class TestIsHotDataServer:

    """
    冷同步热服务
    - 从冷数据表获取出单的Listing数据同步至冷数据打标表，再由另一服务同步至热数据表
    - 从冷数据表获取转FBA的Listing，判断是否存在同ASIN同国家的自发货Listing，同步至冷数据打标表，再由另一服务同步至热数据表
    """
    public_program = public_invoking()

    # 冷同步热 - 满足出单条件数据 >>> 打标表 >>> 热数据表
    def hot_data_marking_base(self, id):

        star_time = time()

        # 获取满足出单条件数据
        erp_sql = f"SELECT OrderSourceSKUID FROM RB_Amazon_Product_Base ( NOLOCK ) " \
                  f"WHERE OrderSourceSKUID IN ( SELECT id FROM dbo.RB_Product_OrderSourceSKU ( NOLOCK ) WHERE CustomerID = 1 AND OrderSourceID = {id} AND isDelete = 0 ) " \
                  f"AND IsDelete = 0;"
        issue_list = self.public_program.erp_db(erp_sql)

        # 以字符串形式获取出单数据的渠道SKUID "111,222,333"
        lis = []
        for i in issue_list:
            for type, value in i.items():
                temps = value
                lis.append(str(temps))
        OrderSourceSkuId = ",".join(lis)

        # 根据渠道ID获取来源渠道对应的部门表ID
        ordersource_sql = f"select DepartmentId from aml_department_ordersource where OrderSourceId in ({id})"
        cold_id = self.public_program.cold_db(ordersource_sql)
        # 对部门表ID进行去重
        lis = []
        for i in cold_id:
            if i not in lis:
                lis.append(i)
        # 推导式将字典的key值存进列表
        ordersource_base = [n["DepartmentId"] for n in lis]
        cold_data = []
        # 遍历获取不同部门表的渠道数据
        for j in ordersource_base:
            sql = f"SELECT OrderSourceSKU, ASINorItemID, SKU, CONVERT(IsHotData, SIGNED )AS IsHotData FROM aml_amazon_product_base_dep{j}" \
                  f" WHERE OrderSourceID in ({id}) AND OrderSourceSKUID IN ({OrderSourceSkuId});"
            data = self.public_program.cold_db(sql)
            cold_data += data

        for i in cold_data:
            if i["IsHotData"] == 0:
                Listing_Error.logger.error(f"{i}>>>>>>>>>存在异常")
            # else:
            #     pass

        end_time = time()
        print(f"检测完成,耗时{round(end_time - star_time, 2)}")

        # report = f"ERP满足出单数据{len(issue_list)}条   \n" \
        #          f"同步至打标表 RB_Amazon_Product_Base_Marking数据{len(marking_data)}条    \n" \
        #          f"同步至临时表 RB_Amazon_Product_Base_ColdHot_Temp数据{len(temp_data)}条    \n" \
        #          f"发现异常数据{sum_error_data}"
        # return report

    # 冷同步热,满足Listing数据转FBA条件,同ASIN同国家都转为热数据
    def fba_change_hotdata(self, id, changetime):

        # 根据渠道ID获取来源渠道对应的部门表ID
        ordersource_sql = f"select DepartmentId from aml_department_ordersource where OrderSourceId in ({id})"
        cold_id = self.public_program.cold_db(ordersource_sql)
        # 对部门表ID进行去重
        lis = []
        for i in cold_id:
            if i not in lis:
                lis.append(i)
        # 推导式将字典的key值存进列表
        ordersource_base = [n["DepartmentId"] for n in lis]

        # 根据ChangeToFBATime获取转FBA的Listing数据
        data = []
        for j in ordersource_base:
            fba_sql = f"SELECT ASINorItemID, OrderSourceCountry FROM aml_amazon_product_base_dep{j} " \
                      f"WHERE OrderSourceID IN ({id}) AND ChangeToFBATime >= '{changetime}'"
            change_fba_data = self.public_program.cold_db(fba_sql)
            data.append(change_fba_data)

        sign = {"IsHotData": 0}
        for i in ordersource_base:
            for n in data:
                for a in n:
                    sql = f"SELECT CONVERT(IsHotData, SIGNED )AS IsHotData FROM aml_amazon_product_base_dep{i} " \
                          f"WHERE ASINorItemID = '{a['ASINorItemID']}' AND OrderSourceCountry = '{a['OrderSourceCountry']}';"
                    res = self.public_program.cold_db(sql)
                    if sign in res:
                        Listing_Error.logger.error(f"{a}>>>>>>>>>存在异常")
                    else:
                        print(f"{a}>>>>>>>>>数据正常")




if __name__ == '__main__':

    # # 满足出单同步至打标表
    # id = '5269'
    # TestIsHotDataServer().hot_data_marking_base(id)

    # 冷变热满足转FBA同ASIN同国家
    id = '6895,13189,15413,10528'
    time = '2023-1-1'
    TestIsHotDataServer().fba_change_hotdata(id, time)
